#ifndef __UDP_SERVER_HPP__
#define __UDP_SERVER_HPP__

#include "Comm.hpp"
#include <iostream>
#include <memory>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <strings.h>
#include "Log.hpp"
using namespace LogMudule;
const uint16_t defaultport = 8000;
const int defaultsockfd = -1;


class UdpServer
{
public:
    //构造函数---初始化本地ip和服务器端口
    UdpServer(uint16_t port = defaultport)
    :_port(port),_sockfd(defaultsockfd),_isrunning(false)
    {}
    //初始化工作---创建套接字填写对应信息
    void Init()
    {
        //创建套接字
        _sockfd = socket(AF_INET,SOCK_DGRAM,0);
        if(_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "套接字创建失败";
            Die(SOCKET_ERR);
        }
        LOG(LogLevel::INFO) << "套接字创建成功";
        struct sockaddr_in local;
        bzero(&local,sizeof(local));
        //填写协议家族
        local.sin_family = AF_INET;
        //主机转网络
        local.sin_addr.s_addr = INADDR_ANY;
        //本地序列转网络序列
        local.sin_port = htons(_port);

        //绑定
        int n = bind(_sockfd,(const struct sockaddr*)&local,sizeof(local));
        if(n < 0)
        {
            LOG(LogLevel::FATAL) << "绑定失败";
            Die(BIND_ERR);
        }
        //绑定成功
        LOG(LogLevel::INFO) << "绑定成功";
    }
    //启动服务器
    void Start()
    {
        _isrunning = true;
        while(true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            char buffer[1024];
            //服务器接收消息---需要从远端接受消息
            ssize_t n = recvfrom(_sockfd,buffer,sizeof(buffer) - 1,0,(struct sockaddr*)&peer,&len);

            //收到消息了
            if(n > 0)
            {
                buffer[n] = 0;
                LOG(LogLevel::INFO) << "远端发来的消息是: " << buffer;

                std::string echostring = "echo# ";
                echostring += buffer;

                sendto(_sockfd,echostring.c_str(),echostring.size(),0,(const sockaddr*)&peer,sizeof(peer));
            }
        }
        _isrunning = false;
    }
    ~UdpServer()
    {
    }
private:
    // //点分十进制的IP地址
    // std::string _ip;
    //本地端口
    uint16_t _port;
    //sockfd
    int _sockfd;
    bool _isrunning;
};


#endif